package model

import (
	"OJCenter/global"
	"OJCenter/idl"
	"github.com/mitchellh/mapstructure"
)

func (m *Model) CreateNotice(Notice *idl.Notice) error {
	err := m.N.InsertNoticeInfo(Notice)
	if err != nil {
		return err
	}
	return nil
}

func (m *Model) DeleteNoticeByNID(nids []int64) (int, *[]int64) {
	sum := len(nids)
	var fu []int64
	for _, nid := range nids {
		err := m.N.DeleteNoticeInfo(&idl.Notice{Nid: nid})
		if err != nil {
			sum--
			fu = append(fu, nid)
			global.Logger.Errorf("uid:%v,delete Notice info failed,err:%v", nid, err)
		}
	}
	return sum, &fu
}

func (m *Model) UpdateNotices(Notices *[]idl.Notice) (int, *[]idl.Notice) {
	sum := len(*Notices)
	var fu []idl.Notice
	for _, notice := range *Notices {
		var info map[string]interface{}
		err := mapstructure.Decode(&notice, &info)
		if err != nil {
			fu = append(fu, notice)
			global.Logger.Error("update marshal failed")
			sum--
			continue
		}
		err = m.N.UpdateNoticeInfo(info)
		if err != nil {
			sum--
			fu = append(fu, notice)
			global.Logger.Errorf("id:%v,update Notice info failed,err:%v", notice.Nid, err)
		}
	}
	return sum, &fu
}

func (m *Model) SelectNoticesByCID(Notices *[]idl.Notice) (int, *[]idl.Notice) {
	sum := len(*Notices)
	var fu []idl.Notice
	for _, Notice := range *Notices {
		u, err := m.N.GetNoticeInfo(Notice.Nid)
		if err != nil {
			sum--
			fu = append(fu, *u)
			global.Logger.Errorf("uid:%v,delete Notice info failed,err:%v", Notice.Cid, err)
		}
	}
	return sum, &fu
}
